/**
 * 
 */
package info.niwota.start;

import info.niwota.start.app.AppListActivity;
import info.niwota.start.app.AppLoader;
import android.app.KeyguardManager;
import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.content.IntentFilter;
import android.os.Bundle;
import android.telephony.TelephonyManager;
import android.util.Log;
import android.view.KeyEvent;
import android.view.WindowManager;
import android.widget.Toast;

/**
 * @author qiangli
 * 
 */
public class PowerupActivity extends AppListActivity {
	protected static final String TAG = "PowerupActivity";

	private IntentFilter intentFilter;

	private BroadcastReceiver receiver = new BroadcastReceiver() {

		public void onReceive(Context ctx, Intent intent) {
			final String action = intent.getAction();

			if (Debug.DEBUG) {
				Log.d(TAG, "action: " + action + " paused: " + mPaused);
			}

			if (Intents.ACTION_PHONE_STATE.equals(action)) {
				final String state = intent
						.getStringExtra(TelephonyManager.EXTRA_STATE);

				if (Debug.DEBUG) {
					Log.d(TAG, "phone state change, state: " + state
							+ " extras: " + intent.getExtras());
				}

				if (TelephonyManager.EXTRA_STATE_RINGING.equals(state)) {
					// update
					final boolean active = !mPaused;
					ApplicationContext.setActive(active);

					boolean b = moveTaskToBack(true);

					if (Debug.DEBUG) {
						Log.d(TAG, "phone state change, moved to bg: " + b
								+ " active: " + active);
					}
				}
				return;
			}

			if (Intent.ACTION_SCREEN_OFF.equals(action)) {
				boolean b = moveTaskToBack(true);

				if (Debug.DEBUG) {
					Log.d(TAG, "screen off, moved to bg: " + b);
				}
				
				return;
			}
			
			// give way to alarms
			if (Intents.ALARM_ALERT.equals(action) 
					|| Intents.ALARM_ALERT1.equals(action)
					|| Intents.ALARM_ALERT2.equals(action)
					|| Intents.ALARM_ALERT_SAMSUNG.equals(action)) {
				boolean b = moveTaskToBack(true);

				if (Debug.DEBUG) {
					Log.d(TAG, "alarm off, moved to bg: " + b);
				}
				
				return;
			}
		}
	};

	private boolean mPaused = true;

	@Override
	public void onCreate(Bundle savedInstanceState) {
		getWindow().addFlags(WindowManager.LayoutParams.FLAG_SHOW_WHEN_LOCKED);
		
		super.onCreate(savedInstanceState);

		//
		intentFilter = new IntentFilter();
		intentFilter.addAction(Intent.ACTION_SCREEN_ON);
		intentFilter.addAction(Intent.ACTION_SCREEN_OFF);
		
		intentFilter.addAction(Intents.ACTION_PHONE_STATE);
		
		// alarm
		intentFilter.addAction(Intents.ALARM_ALERT);
		intentFilter.addAction(Intents.ALARM_ALERT1);
		intentFilter.addAction(Intents.ALARM_ALERT2);
		intentFilter.addAction(Intents.ALARM_ALERT_SAMSUNG);
	}

	@Override
	protected void onPause() {
		if (Debug.DEBUG) {
			Log.d(TAG, "onPause");
		}

		super.onPause();

		try {
			unregisterReceiver(receiver);
		} catch (Exception e) {
			e.printStackTrace();
		}

		mPaused = true;
	}

	@Override
	protected void onResume() {
		if (Debug.DEBUG) {
			Log.d(TAG, "onResume");
		}
		super.onResume();
		
		mPaused = false;
		registerReceiver(receiver, intentFilter);

	}

	@Override
	public boolean onKeyDown(int keyCode, KeyEvent event) {
		return true;
	}

	@Override
	protected void loadApps() {
		apps.clear();
		apps.addAll(AppLoader.loadPowerup(this));
	}

	private static KeyguardManager km = null;

	synchronized private static boolean isKeygarded(Context ctx) {
		if (km == null) {
			km = (KeyguardManager) ctx.getSystemService(Context.KEYGUARD_SERVICE);
		}
		
		boolean mode = km.inKeyguardRestrictedInputMode();
		
		if (Debug.DEBUG) {
			Log.d(TAG, "isKeyguarded mode: " + mode);
		}
		
		return mode;
	}
	
	public static void ensureIfRunning(Context ctx) {
		ensureIfRunning(ctx, false);
	}
	
	public static void ensureIfRunning(Context ctx, boolean quit) {
		final boolean running = Preferences.getRunningStatus(ctx);
		
		final Intent last = Preferences.getLastApp(ctx);
		
		final boolean guarded = isKeygarded(ctx);
		
		if (Debug.DEBUG) {
			Log.d(TAG, "ensureRunning quit: "+ quit + " running: " + running + " last: " + last + " guarded: " + guarded);
		}
		
		if (!running) {
			if (Debug.DEBUG) {
				Log.d(TAG, "not running, ignored");
			}
			return;
		}
		
		if (!guarded) {
			if (Debug.DEBUG) {
				Log.d(TAG, "not guarded, ignored");
			}
			return;
		}
		
		if (quit || last == null) {
			launchPowerup(ctx);
		} else {
			launch(ctx, last);
		}
	}
	
	private static void launchPowerup(Context ctx) {
		try {
			Intent i = new Intent(ctx, PowerupActivity.class);
			
			i.addFlags(Intent.FLAG_ACTIVITY_EXCLUDE_FROM_RECENTS);
			i.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
			i.addFlags(Intent.FLAG_ACTIVITY_NO_HISTORY);
			i.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);
			i.addFlags(Intent.FLAG_ACTIVITY_SINGLE_TOP);
			
			//
			ctx.startActivity(i);
			
			//clear
			Preferences.putLastApp(ctx, null);
		} catch (Exception e) {
			e.printStackTrace();
		}
	}

	protected void doOpen(ResourceInfo item) {
		Intent i = item.getIntent();
		launch(this, i);
	}

	private static void launch(Context ctx, Intent i) {
		try {
			i.putExtra("extra.restricted", true);
			i.addFlags(Intent.FLAG_ACTIVITY_EXCLUDE_FROM_RECENTS);
			i.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
			i.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);
			i.addFlags(Intent.FLAG_ACTIVITY_SINGLE_TOP);
			
			i.addFlags(Intent.FLAG_ACTIVITY_RESET_TASK_IF_NEEDED);
			//
			i.addFlags(Intent.FLAG_FROM_BACKGROUND);
			i.addFlags(Intent.FLAG_ACTIVITY_NO_USER_ACTION);
			i.addFlags(Intent.FLAG_ACTIVITY_NO_ANIMATION);
			
			if (Debug.DEBUG) {
				Log.d(TAG, "doOpen Intent " + i);
				Log.d(TAG, "doOpen Extras: " + i.getExtras());
			}

			ctx.startActivity(i);
			
			//save
			Preferences.putLastApp(ctx, i);
		} catch (Exception e) {
			Toast.makeText(ctx, e.getMessage(), Toast.LENGTH_SHORT);
		}
	}
}
